package com.pearadmin.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pearadmin.common.nucleus.base.BaseController;
import com.pearadmin.common.nucleus.domain.request.PageParam;
import com.pearadmin.common.nucleus.domain.response.Result;
import com.pearadmin.common.tool.encode.MD5Util;
import com.pearadmin.system.domain.SysRole;
import com.pearadmin.system.domain.SysUserRole;
import com.pearadmin.system.service.ISysRoleService;
import com.pearadmin.system.service.ISysUserRoleService;
import com.pearadmin.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.pearadmin.system.domain.SysUser;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;


@Api(tags = {"用户管理"})
@RestController
@RequestMapping("system/user")
public class SysUserController extends BaseController {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysRoleService sysRoleService;
    @Resource
    private ISysUserRoleService sysUserRoleService;

    private String MODULE_PATH = "system/user/";

    @ApiOperation(value = "用户视图")
    @GetMapping("main")
    public ModelAndView main(ModelAndView modelAndView){
        modelAndView.setViewName(MODULE_PATH + "main");
        return modelAndView;
    }

    @ApiOperation(value = "分页列表")
    @GetMapping("data")
    public Object data(SysUser sysUser, PageParam pageParam){
        IPage<SysUser> pageInfo = sysUserService.page(new Page<>(pageParam.getPage(),pageParam.getLimit()),null);
        return PageTable(pageInfo.getRecords(),pageInfo.getTotal());
    }

    @ApiOperation(value = "新增用户")
    @GetMapping("add")
    public ModelAndView add(ModelAndView modelAndView){
        modelAndView.addObject("roles",sysRoleService.list(null));
        modelAndView.setViewName(MODULE_PATH + "add");
        return modelAndView;
    }

    @ApiOperation(value = "保存用户")
    @Transactional
    @PostMapping("save")
    public Result add(@RequestBody SysUser sysUser){
        sysUser.setPassword(MD5Util.getMD5(sysUser.getPassword()));
        boolean result = sysUserService.save(sysUser);
        for (String roleId:  Arrays.asList(sysUser.getRoles().split(","))) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(sysUser.getId());
            sysUserRoleService.save(sysUserRole);
        }
        return choice(result,"保存成功","保存失败");
    }

    @ApiOperation(value = "修改视图")
    @GetMapping("edit")
    public ModelAndView edit(ModelAndView modelAndView,String id){
        //查询用户个人信息
        SysUser  sysUser =  sysUserService.getById(id);
        //查询角色列表
        List<SysRole> sysRoles = sysRoleService.list(null);
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<SysUserRole> myRoles= sysUserRoleService.list(queryWrapper);
        for (SysRole role:sysRoles) {
            for (SysUserRole userRole:myRoles){
                if(userRole.getRoleId().equals(role.getId())){
                    role.setChecked(true);
                }
            }
        }
        modelAndView.addObject("sysRoles",sysRoles);
        modelAndView.addObject("sysUser",sysUser);
        modelAndView.setViewName(MODULE_PATH + "edit");
        return modelAndView;
    }

    @ApiOperation(value = "修改用户")
    @PutMapping("update")
    public Result edit(@RequestBody SysUser sysUser){
        //清除用户绑定的信息
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",sysUser.getId());
        boolean b = sysUserRoleService.remove(queryWrapper);
        for (String roleId: Arrays.asList(sysUser.getRoles().split(","))) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(sysUser.getId());
            sysUserRoleService.save(sysUserRole);
        }
        boolean result = sysUserService.updateById(sysUser);
        return choice(result,"修改成功","修改失败");
    }

    @ApiOperation(value = "开启用户")
    @PutMapping("enable/{id}")
    public Result enable(@PathVariable String id){
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setStatus("0");

        boolean result = sysUserService.updateById(sysUser);
        return choice(result);
    }

    @ApiOperation(value = "禁用用户")
    @PutMapping("disable/{id}")
    public Result disable(@PathVariable String id){
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setStatus("1");

        boolean result = sysUserService.updateById(sysUser);
        return choice(result);
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("deleteById/{id}")
    public Result deleteById(@PathVariable("id") String id){
        boolean result = sysUserService.removeById(id);
        return choice(result);
    }

    @ApiOperation(value = "批量删除")
    @DeleteMapping("deleteByIds/{ids}")
    public Result deleteByIds(@PathVariable("ids") String ids){
        boolean result = sysUserService.removeByIds(ids.split(","));
        return choice(result,"删除成功","删除失败");
    }
}
